﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data;
using Microsoft.SharePoint;
using System.Xml;
using System.Web.UI.WebControls;
using System.Web;
using System.Net.Mail;
using Microsoft.SharePoint.Administration.Claims;
using Microsoft.SharePoint.Utilities;
using System.DirectoryServices.AccountManagement;
using Microsoft.SharePoint.Administration;

namespace MII_FIF.Layouts
{
    public static class Configuration
    {
        public static string DBConnection()
        {
            return System.Configuration.ConfigurationManager.ConnectionStrings["InventoryManagement"].ConnectionString;
        }

        public static string DocLibName()
        {
            return "Attachments";
        }

        public static string ApproverGroupName()
        {
            return "Approver";
        }
        public const string DeviceManagementGroupName = "IMS Device Management";
        public const string WorkOrderGroupName = "IMS Work Order";
        public const string MasterGroupName = "IMS Master";
        public const string ManagePDGroupName = "IMS Manage Physical";
        public const string DataCabangGroupName = "IMS Data Cabang";
        public const string DataKunjunganGroupName = "IMS Data Kunjungan";
        public const string ChangeRequestGroupName = "IMS Change Request";
        public const string ChecklistGroupName = "IMS Checklist";
        public const string ReportGroupName = "IMS Report"; 
    }

    public static class Generic
    {
        public static bool isFullControl()
        {
            bool checkPermission = false;
            SPSite site = new SPSite(SPContext.Current.Site.ID);
            SPWeb web = site.OpenWeb();
            
            SPRoleDefinitionBindingCollection usersRoles = web.AllRolesForCurrentUser;
            SPRoleDefinitionCollection roleDefinitions = web.RoleDefinitions;
            SPRoleDefinition roleDefinition = roleDefinitions["Full Control"];
            if (usersRoles.Contains(roleDefinition))
            {
                checkPermission = true;
            }
            return checkPermission;
        }

        public static bool IsUserInGroup(string groupname)
        {
            SPDiagnosticsService.Local.WriteTrace(0, new SPDiagnosticsCategory("MII", TraceSeverity.Verbose, EventSeverity.Information), TraceSeverity.Verbose, "enter user in group");
            SPDiagnosticsService.Local.WriteTrace(0, new SPDiagnosticsCategory("MII", TraceSeverity.Verbose, EventSeverity.Information), TraceSeverity.Verbose, "groupname : " + groupname);
            bool ret = false;
            //SPSecurity.RunWithElevatedPrivileges(delegate
            //{
                using (SPSite site = new SPSite(SPContext.Current.Site.ID))
                {
                    using (SPWeb web = site.OpenWeb())
                    {
                        foreach (SPGroup group in web.Groups)
                        {
                            SPDiagnosticsService.Local.WriteTrace(0, new SPDiagnosticsCategory("MII", TraceSeverity.Verbose, EventSeverity.Information), TraceSeverity.Verbose, "group name : " + group.Name);
                            if (group.Name.Equals(groupname))
                            {
                                SPDiagnosticsService.Local.WriteTrace(0, new SPDiagnosticsCategory("MII", TraceSeverity.Verbose, EventSeverity.Information), TraceSeverity.Verbose, "found same name");
                                ret = group.ContainsCurrentUser;
                                SPDiagnosticsService.Local.WriteTrace(0, new SPDiagnosticsCategory("MII", TraceSeverity.Verbose, EventSeverity.Information), TraceSeverity.Verbose, "ret on name : " + ret);
                            }
                        }
                        
                    }
                }
            //});
            SPDiagnosticsService.Local.WriteTrace(0, new SPDiagnosticsCategory("MII", TraceSeverity.Verbose, EventSeverity.Information), TraceSeverity.Verbose, "end ret : " + ret);
            return ret;
        }

        public static DataTable getDataTableFromList(string ListName)
        {
            DataTable dt = null;
            SPWeb web = SPContext.Current.Web;
            SPList List = web.Lists.TryGetList(ListName);
            if (List != null)
            {
                dt = List.Items.GetDataTable();
                for (int i = 0; i < List.Items.Fields.Count; i++)
                {
                    string namaField = List.Items.Fields[i].ToString();
                    string InternalName = System.Web.HttpUtility.HtmlDecode(List.Items.Fields[i].InternalName.ToString());

                    if (dt.Columns.Contains(InternalName))
                    {
                        if (!dt.Columns.Contains(namaField))
                            dt.Columns[InternalName].ColumnName = XmlConvert.DecodeName(namaField);
                    }
                }
            }
            //kalo return dt nya null = tidak nemu listnya (biasanya salah name).
            //kalo return dtnya gk null, berarti dpt list dan isinya.
            return dt;
        }

        public static SPListItem getSPLIstItemsFromDataTable(string ListName, int ID)
        {
            SPListItem Item = null;
            SPWeb web = SPContext.Current.Web;
            SPList List = web.Lists.TryGetList(ListName);
            if (List != null)
            {
                if (List.Items.Count > 0)
                {
                    Item = List.Items.GetItemById(ID);
                }
            }
            //kalo return Item nya null = tidak nemu item (biasanya salah name atau emank gk ada item nya).
            //kalo return Item gk null, berarti dpt list item nya.
            return Item;
        }

        public static String getItemsFromDataTable(string ListName, int ID, string NamaField)
        {
            string Value = "";
            SPListItem Item = null;
            SPWeb web = SPContext.Current.Web;
            SPList List = web.Lists.TryGetList(ListName);
            if (List != null)
            {
                if (List.Items.Count > 0)
                {
                    Item = List.Items.GetItemById(ID);
                    if (Item != null)
                        Value = Item[NamaField].ToString();
                }
            }
            return Value;
        }

        public static string GetUserLoginReformat()
        {
            if (SPContext.Current.Web.CurrentUser.LoginName.Contains('|'))
                return SPContext.Current.Web.CurrentUser.LoginName.Split('|')[1].ToString();
            else
                return SPContext.Current.Web.CurrentUser.LoginName.ToString();
        }

        public static DropDownList BindDDL(DropDownList DDL, DataTable DT, string DataTextField, string DataValueField)
        {
            if (DT.Columns.Contains("IsDeleted"))
            {
                foreach (DataRow row in DT.Rows)
                {
                    if (row["IsDeleted"].ToString().ToLower() == "true")
                    {
                        row.Delete();
                    }
                }
                DataView DV = DT.DefaultView;
                DV.Sort = DataTextField + " ASC";
                DT = DV.ToTable();

                DDL.DataSource = DT;
                DDL.DataTextField = DataTextField;
                DDL.DataValueField = DataValueField;
                DDL.DataBind();
                DDL.Items.Insert(0, new ListItem("--Please Select--", "-1"));
                DDL.SelectedIndex = 0;
            }
            else
            {
                DataView DV = DT.DefaultView;
                DV.Sort = DataTextField + " ASC";
                DT = DV.ToTable();

                DDL.DataSource = DT;
                DDL.DataTextField = DataTextField;
                DDL.DataValueField = DataValueField;
                DDL.DataBind();
                DDL.Items.Insert(0, new ListItem("--Please Select--", "-1"));
                DDL.SelectedIndex = 0;
            }
            return DDL;
        }

        public static DropDownList BindDDL(DropDownList DDL, System.Collections.CollectionBase col, string DataTextField, string DataValueField)
        {
            DDL.DataSource = col;
            DDL.DataTextField = DataTextField;
            DDL.DataValueField = DataValueField;
            DDL.DataBind();
            DDL.Items.Insert(0, new ListItem("--Please Select--", "-1"));
            DDL.SelectedIndex = 0;
            return DDL;
        }

        public static DataTable SortDataTable(string columnName,string descasc, DataTable Datatable)
        {
            DataTable DT = Datatable;
            DataView DV = DT.DefaultView;
            DV.Sort = columnName+" "+descasc;
            DT = DV.ToTable();
            return DT;
        }

        public static string GenLink(string Link)
        {
            return SPContext.Current.Site.OpenWeb().Url + Link;
        }

        public static string UploadFile(FileUpload FU)
        {
            HttpPostedFile file = FU.PostedFile;
            string url = "";
            if (file.ContentLength > 0)
            {
                SPSecurity.RunWithElevatedPrivileges(delegate
                {
                    string filename = FU.FileName;
                    byte[] inputbuff = new Byte[file.ContentLength];
                    System.IO.Stream filestream;
                    filestream = file.InputStream;
                    filestream.Read(inputbuff, 0, file.ContentLength);

                    SPSite _site = new SPSite(SPContext.Current.Web.Site.ID);
                    SPWeb _web = _site.OpenWeb();
                    url = _web.Url + "/" + Configuration.DocLibName() + "/" + DateTime.Now.ToString("ddMMyyhhmmss") + "_" + filename;

                    _web.AllowUnsafeUpdates = true;
                    SPFile uploadedFile = _web.Files.Add(url, inputbuff);
                    _web.AllowUnsafeUpdates = false;
                });
            }
            return url;
        }

        public static bool checkUploadedFileName(string FileName)
        {
            bool contain = false;
            char[] restricted = new char[12] { '#', '%', '&', '*', ':', '<', '>', '?', '/', '{', '|', '}' };
            for (int i = 0; i < restricted.Length; i++)
            {
                if (FileName.Contains(restricted[i]))
                {
                    contain = true;
                    break;
                }
            }
            return contain;
        }

        public static string getEmailUser(string name)
        {
            string email = "";

            if (name.ToString().ToLower().Contains('|'))
            {
                SPWeb web = SPContext.Current.Web;
                email = web.AllUsers[name].Email;
            }
            else
            {
                //PrincipalContext context = new PrincipalContext(ContextType.Domain);
                //UserPrincipal user = UserPrincipal.FindByIdentity(context, name);
                //email = user.EmailAddress;
                SPWeb web = SPContext.Current.Web;
                SPClaimProviderManager cpm = SPClaimProviderManager.Local;
                SPClaim userClaim = cpm.ConvertIdentifierToClaim(name, SPIdentifierTypes.WindowsSamAccountName);
                using (SPSite site = new SPSite(SPContext.Current.Web.Url))
                {
                    SPUser user = site.RootWeb.EnsureUser(userClaim.ToEncodedString());
                    email = user.Email;
                }
            }

            return email;
        }

        public static string getUserName(string login)
        {
            string email = "";

            if (login.ToString().ToLower().Contains('|'))
            {
                SPWeb web = SPContext.Current.Web;
                email = web.AllUsers[login].Name;
            }
            else
            {
                //PrincipalContext context = new PrincipalContext(ContextType.Domain);
                //UserPrincipal user = UserPrincipal.FindByIdentity(context, name);
                //email = user.EmailAddress;
                SPWeb web = SPContext.Current.Web;
                SPClaimProviderManager cpm = SPClaimProviderManager.Local;
                SPClaim userClaim = cpm.ConvertIdentifierToClaim(login, SPIdentifierTypes.WindowsSamAccountName);
                using (SPSite site = new SPSite(SPContext.Current.Web.Url))
                {
                    SPUser user = site.RootWeb.EnsureUser(userClaim.ToEncodedString());
                    email = user.Name;
                }
            }

            return email;
        }

        public static bool isApprover()
        {
            bool check = true;
            SPWeb web = SPContext.Current.Web;
            check = web.Groups[Configuration.ApproverGroupName()].ContainsCurrentUser;
            return check;
        }

        public static string GetFileNameFromUrl(string url)
        {
            string filename = string.Empty;
            if (!string.IsNullOrEmpty(url))
            {
                filename = System.IO.Path.GetFileName(new Uri(url).AbsolutePath);
            }
            return filename;
        }

        public static void sendEmailSMTP(string from, string To, string subject, string body)
        {
            MailMessage mail = new MailMessage(from, To, subject, body);
            SmtpClient client = new SmtpClient();
            client.Port = 25;
            client.DeliveryMethod = SmtpDeliveryMethod.Network;
            client.UseDefaultCredentials = false;
            client.Host = System.Configuration.ConfigurationManager.ConnectionStrings["InventoryManagementMail"].ConnectionString;
            mail.IsBodyHtml = true;
            mail.Subject = subject;
            mail.Body = body;
            client.Send(mail);
        }
    }
    public static class word
    {
        public const string Approve = "Approve";
        public const string Reject = "Reject";
        public const string Rejected = "Rejected";
        public const string Approved = "Approved";
        public const string WaitingforApproval = "Waiting for approval";
        public const string Descending = "DESC";
        public const string Ascending = "ASC";        
    }

}
